package com.catcoin.deposit.scheduledExecutorService;



import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.catcoin.deposit.model.*;
import com.catcoin.deposit.service.*;
import com.catcoin.deposit.util.StringUtils;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static org.springframework.transaction.annotation.Propagation.*;

@Component
@Log
public class ScheduledService {

    @Autowired
    private ILogMailccService iLogMailccService;
    @Autowired
    private ILogStatedccService iLogStatedccService;
    @Autowired
    private IAccountService iAccountService;
    @Autowired
    private IUsablecatccService iUsablecatccService;
    @Autowired
    private ISysConfigsService iConfigsService;

    @Autowired
    private ToolfeignInterface toolfeignInterface;

    private BigDecimal cvMaoBiRatio = new BigDecimal(0.5);//猫币千分之二50%
    private BigDecimal cvXiaoFeiRatio = new BigDecimal(0.5);//消费千分之二50%

    @Scheduled(cron = "0 30 0 * * ?")
    @Transactional
    public void hhtbMailcc(){
        try {
            System.out.println("**********************开始定时任务**********************");
            //查询配置属性表
            SysConfigs configs = new SysConfigs();
            configs.setFieldCode("statedccToForce");
            EntityWrapper<SysConfigs> entityWrapper = new EntityWrapper<SysConfigs>(configs);
            configs = iConfigsService.selectOne(entityWrapper);
            cvMaoBiRatio = new BigDecimal(configs.getFieldValue()).divide(new BigDecimal(100));

            configs.setFieldCode("statedccToBlancecc");
            configs = iConfigsService.selectOne(entityWrapper);
            cvXiaoFeiRatio = new BigDecimal(configs.getFieldValue()).divide(new BigDecimal(100));
            //查询用户表
            List<UsablecatccDto> usablecatccDtoList = iUsablecatccService.selectAllq2List();
            //计算猫币定期千分之二的50%
            //插入猫币定期记录
            //插入消费账户表记录
            Boolean isOk = blanceccMailcc50(usablecatccDtoList);

            System.out.println("**********************结束定时任务**********************");
        }catch (Exception e){
            log.info(e.getMessage());
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            System.out.println("**********************定时任务异常**********************");
        }

    }

    //计算猫币定期千分之二的50%
    @Transactional(propagation= REQUIRED)
    public Boolean  blanceccMailcc50(List<UsablecatccDto> usablecatccDtoList){

        List<Usablecatcc> inUsablecatccList = new ArrayList<>();//批量修改用户账户表充值数据
        List<Account> inAccountsList = new ArrayList<>();       //批量修改用户账户表
        List<LogStatedcc> inStatedccList = new ArrayList<>();   //新增猫币定期流水表
        List<LogMailcc> inMailccList = new ArrayList<>();       //新增用户消费账户流水表
        Boolean isOk = false;   //是否批量更新成功
        Integer isUpdate = 0, //是否有修改
                listIndex = 0, //下标位置
                listSize = usablecatccDtoList.size();//集合总数
        if(usablecatccDtoList.size()>0){
            Account account2 = new Account();//循环用
            for (UsablecatccDto ad:usablecatccDtoList) {
                //查询交易用户id
                String jiaoYiUserId = selectJiaoYiSuo(ad.getUserPhone());
                if(!"error".equals(jiaoYiUserId) /*&& (ad.getStatedcc2().compareTo(BigDecimal.ONE)==1)*/){
                    BigDecimal stateMaoBiNum = ad.getStatedcc2().multiply(cvMaoBiRatio).setScale(6,BigDecimal.ROUND_DOWN);//千分之二的50%
                    BigDecimal stateXiaoFeiNum = ad.getStatedcc2().multiply(cvXiaoFeiRatio).setScale(6,BigDecimal.ROUND_DOWN);//千分之二的50%
                    //调用交易所接
                    String result = toolfeignInterface.operate(jiaoYiUserId,"17","1",stateMaoBiNum.toString());
                    if(!"error".equals(result)){
                        JSONObject jsonObject = JSONObject.parseObject(result);
                        if("true".equals(jsonObject.get("isSuc").toString())){
                            isUpdate ++;
                            //修改用户充值表
                            Usablecatcc usablecatcc = updateUsablecatcc(ad);
                            inUsablecatccList.add(usablecatcc);
                            //修改账户表
                            Account account = updateAccount(ad,stateMaoBiNum,stateXiaoFeiNum);
                            account2 = account;//赋值下次比较
                            inAccountsList.add(account);
                            //新增猫币定期表
                            LogStatedcc logStatedcc = insertLogStatedcc(ad,stateMaoBiNum,0);
                            inStatedccList.add(logStatedcc);

                            LogStatedcc logStatedcc1 = insertLogStatedcc(ad,stateXiaoFeiNum,1);
                            inStatedccList.add(logStatedcc1);

                            //新增消费账户流水表
                            LogMailcc logMailcc = insertLogMailcc(ad,stateXiaoFeiNum);
                            inMailccList.add(logMailcc);

                        }

                    }

                }
                if(account2.getId()!=null){
                    //判断是不是同一个用户
                    isSameUser(listIndex,listSize,ad.getUserId(),usablecatccDtoList,account2.getStatedcc(),account2.getBlancecc(),account2.getMailcc());
                }
                listIndex++;
            }
            if(isUpdate.intValue()>0){
                //更新用户账户表
                Boolean us = iUsablecatccService.updateBatchById(inUsablecatccList);
                Boolean ac = iAccountService.updateBatchById(inAccountsList);
                Boolean ls = iLogStatedccService.insertOrUpdateAllColumnBatch(inStatedccList);
                Boolean lm = iLogMailccService.insertOrUpdateAllColumnBatch(inMailccList);
                if(ac && ls && lm && us){
                    isOk = true;
                }
            }
        }
        return isOk;
    }

    //判断list中是不是同一个用户
    public void isSameUser(Integer index, Integer size,Integer userId,List<UsablecatccDto> usablecatccDtoList,BigDecimal statedcc,BigDecimal blancecc,BigDecimal mailcc){
        if(index.intValue() != size.intValue()-1){
            if(userId.intValue() == usablecatccDtoList.get(index+1).getUserId()) {
                usablecatccDtoList.get(index + 1).setStatedcc(statedcc);
                usablecatccDtoList.get(index + 1).setBlancecc(blancecc);
                usablecatccDtoList.get(index + 1).setMailcc(mailcc);
            }
        }
    }

    //修改用户充值表
    public Usablecatcc updateUsablecatcc(UsablecatccDto ad) {
        Usablecatcc usablecatcc = new Usablecatcc();
        usablecatcc.setId(ad.getId());
        usablecatcc.setUserId(ad.getUserId());
        usablecatcc.setOrderNo(ad.getOrderNo());
        usablecatcc.setUsablecatcc(ad.getUsablecatcc().setScale(6,BigDecimal.ROUND_DOWN));
        usablecatcc.setRemainderCatcc(ad.getUsablecatcc().subtract(ad.getStatedcc2()));
        usablecatcc.setCreattime(ad.getCreattime());
        usablecatcc.setChangetime(new Date());
        return  usablecatcc;
    }

    //添加猫币定期流水表
    public LogStatedcc insertLogStatedcc(UsablecatccDto usablecatcc,BigDecimal stateNum,int type){
        LogStatedcc logStatedcc = new LogStatedcc();
        logStatedcc.setUserId(usablecatcc.getUserId());
        logStatedcc.setFromId(usablecatcc.getUserId());
        logStatedcc.setOrderNo(StringUtils.getOrderIdByTime("6"));

        if(type == 0){
            logStatedcc.setRemark("每天转换猫币消费");
            logStatedcc.setPreStatedcc(usablecatcc.getStatedcc());
        }else{
            logStatedcc.setRemark("每天转换用户消费");
            logStatedcc.setPreStatedcc(usablecatcc.getStatedcc().subtract(stateNum));
        }
        logStatedcc.setStatedcc(stateNum);
        logStatedcc.setStatedccType(-1);
        logStatedcc.setDataFlag(1);
        logStatedcc.setCreateTime(new Date());
        logStatedcc.setType(2);//转换获得
        return logStatedcc;
    }
    //添加用户消费账户流水表
    public LogMailcc insertLogMailcc(UsablecatccDto account,BigDecimal stateNum){
        LogMailcc logMailcc = new LogMailcc();
        logMailcc.setUserId(account.getUserId());
        logMailcc.setFromId(account.getUserId());
        logMailcc.setOrderNo(StringUtils.getOrderIdByTime("6"));
        logMailcc.setPreMailcc(account.getMailcc());
        logMailcc.setMailcc(stateNum);
        logMailcc.setMailccType(1);
        logMailcc.setRemark("每天转换获得");
        logMailcc.setDataFlag(1);
        logMailcc.setCreateTime(new Date());
        logMailcc.setType(2);//转换获得
        return logMailcc;
    }

    //修改账户表
    public Account updateAccount(UsablecatccDto ad,BigDecimal stateMaoBiNum,BigDecimal stateXiaoFeiNum){
        Account account = new Account();
        account.setId(ad.getAccountId());
        account.setStatedcc(ad.getStatedcc().subtract(ad.getStatedcc2()));
        account.setBlancecc(ad.getBlancecc().add(stateMaoBiNum));
        account.setMailcc(ad.getMailcc().add(stateXiaoFeiNum));
        return account;
    }
    //获取交易所用户id
    public String selectJiaoYiSuo(String userPhone){

        String result = toolfeignInterface.register(userPhone);

        if(!"error".equals(result)){
            JSONObject jsonObject = JSONObject.parseObject(result);
            if("true".equals(jsonObject.get("isSuc").toString())){
                JSONObject jsonObject1 = JSONObject.parseObject(jsonObject.get("datas").toString());
                return jsonObject1.get("userID").toString();
            }

        }
        return "error";
    }


}
